import { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import "./index.css";

// 获取当前用户的 ID（示例方法）
const getCurrentUserId = () => {
    // 例如，从本地存储或上下文中获取
    return parseInt(localStorage.getItem('userId'), 10) || 1; // 示例用户 ID，实际应用中应动态获取
};

// 轮播组件
function MotivationalCarousel({ messages, interval = 3000 }) {
    const [currentIndex, setCurrentIndex] = useState(0);

    useEffect(() => {
        const timer = setInterval(() => {
            setCurrentIndex((prevIndex) => (prevIndex + 1) % messages.length);
        }, interval);
        return () => clearInterval(timer);
    }, [messages, interval]);

    return (
        <div className="carousel">
            <p className="carousel-message">{messages[currentIndex]}</p>
        </div>
    );
}

// 进度条组件
function ProgressBar({ percentage }) {
    return (
        <div className="progress-bar">
            <div
                className="progress-bar-fill"
                style={{ width: `${percentage}%` }}
            >
                {percentage}%
            </div>
        </div>
    );
}

// 主组件
function Progress() {
    const navigate = useNavigate();
    const userId = getCurrentUserId(); // 获取当前用户 ID

    // 每日目标状态
    const [dailyGoal, setDailyGoal] = useState({
        description: "30分钟练习",
        completedMinutes: 20,
        totalMinutes: 30,
    });

    // 用户学习数据状态
    const [usersProgress, setUserProgress] = useState(null);

    // 选课功能状态
    const [availableCourses, setAvailableCourses] = useState([]);
    const [enrolledCourses, setEnrolledCourses] = useState([]);
    const [enrolling, setEnrolling] = useState(false);
    const [enrollError, setEnrollError] = useState(null);

    // 加载和错误状态
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    // 激励话语
    const motivationalMessages = [
        "坚持下去，你会看到更好的自己！",
        "每一天的努力都在为成功铺路！",
        "伟大的事情从来都是一步步完成的。",
        "学习是改变未来的钥匙！",
        "相信你自己，你可以做到！",
    ];

    // 从后端获取用户学习进度数据
    const fetchUserProgress = useCallback(async () => {
        try {
            setLoading(true);
            const response = await axios.get(`/api/user-progress/${userId}`);
            setUserProgress(response.data);
            setError(null);
        } catch (error) {
            console.error("获取用户进度时出错:", error);
            setError("无法获取用户进度，请稍后再试。");
        } finally {
            setLoading(false);
        }
    }, [userId]);

    // 从后端获取可选课程数据
    const fetchAvailableCourses = useCallback(async () => {
        try {
            const response = await axios.get(`/api/available-courses/${userId}`);
            setAvailableCourses(response.data);
            setError(null);
        } catch (error) {
            console.error("获取可选课程时出错:", error);
            setError("无法获取可选课程，请稍后再试。");
        }
    }, [userId]);

    // 从后端获取已选课程数据
    const fetchEnrolledCourses = useCallback(async () => {
        try {
            const response = await axios.get(`/api/enrolled-courses/${userId}`);
            setEnrolledCourses(response.data);
            setError(null);
        } catch (error) {
            console.error("获取已选课程时出错:", error);
            setError("无法获取已选课程，请稍后再试。");
        }
    }, [userId]);

    // 进行选课操作
    const enrollInCourse = async (courseId) => {
        try {
            setEnrolling(true);
            const response = await axios.post(`/api/enroll-course/${userId}`, { courseId });
            if (response.status === 200) {
                // 选课成功，刷新已选课程和可选课程列表
                fetchEnrolledCourses();
                fetchAvailableCourses();
                setEnrollError(null);
            } else {
                setEnrollError("选课失败，请稍后再试。");
            }
        } catch (error) {
            console.error("选课时出错:", error);
            setEnrollError("选课失败，请稍后再试。");
        } finally {
            setEnrolling(false);
        }
    };

    useEffect(() => {
        // 加载用户进度和课程数据
        fetchUserProgress();
        fetchAvailableCourses();
        fetchEnrolledCourses();

        // 设置轮询，每60秒刷新一次数据
        const intervalId = setInterval(() => {
            fetchUserProgress();
            fetchAvailableCourses();
            fetchEnrolledCourses();
        }, 60000);

        // 清理定时器
        return () => clearInterval(intervalId);
    }, [fetchUserProgress, fetchAvailableCourses, fetchEnrolledCourses]);

    // 计算四级目标整体进度
    const overallProgress = useMemo(() => {
        if (!usersProgress) return 0;

        // 四级目标配置
        const goal = {
            vocabularyMastered: 4500, // 四级需要掌握的单词数量
            listeningHours: 50,       // 听力练习总时长目标（小时）
            mockTestsCompleted: 5,    // 模拟测试目标数量
            totalStudyHours: 100      // 总学习时间目标（小时）
        };

        // 每个目标的权重
        const weights = {
            vocabularyMastered: 0.4,  // 词汇占比 40%
            listeningHours: 0.3,      // 听力占比 30%
            mockTestsCompleted: 0.2,  // 模拟测试占比 20%
            totalStudyHours: 0.1      // 总学习占比 10%
        };

        // 计算各子目标的完成进度
        const vocabularyProgress = Math.min(
            (usersProgress.vocabularyMastered / goal.vocabularyMastered) * 100,
            100
        );
        const listeningProgress = Math.min(
            (usersProgress.listeningHours / goal.listeningHours) * 100,
            100
        );
        const mockTestProgress = Math.min(
            (usersProgress.mockTestsCompleted / goal.mockTestsCompleted) * 100,
            100
        );
        const studyHoursProgress = Math.min(
            (usersProgress.totalStudyHours / goal.totalStudyHours) * 100,
            100
        );

        // 根据权重计算整体进度
        const overallProgress =
            weights.vocabularyMastered * vocabularyProgress +
            weights.listeningHours * listeningProgress +
            weights.mockTestsCompleted * mockTestProgress +
            weights.totalStudyHours * studyHoursProgress;

        return Math.round(overallProgress); // 返回百分比
    }, [usersProgress]);

    return (
        <div className="progress-container">
            {/* 四级目标整体进度 */}
            <div className="section">
                <h3>以四级为目标整体进度</h3>
                {loading ? (
                    <p>加载中...</p>
                ) : error ? (
                    <p className="error">{error}</p>
                ) : (
                    <ProgressBar percentage={overallProgress}/>
                )}
            </div>

            {/* 每日目标 */}
            <div className="section">
                <h3>每日目标</h3>
                <p>今日目标: {dailyGoal.description}</p>
                <p>
                    已完成: {dailyGoal.completedMinutes} 分钟 / {dailyGoal.totalMinutes} 分钟
                </p>

                {/* 跳转到学习目标页面 */}
                <button
                    onClick={() => navigate("/DailyGoal")}
                    className="view-goals-button"
                >
                    查看学习目标
                </button>
            </div>

            {/* 用户选课功能 */}
            <div className="section">
                <h3>课程学习</h3>
                {loading ? (
                    <p>加载中...</p>
                ) : error ? (
                    <p className="error">{error}</p>
                ) : (
                    <div className="course-selection">
                        {/* 可选课程列表 */}
                        {/*<h4>已选课程</h4>*/}
                        {/*{availableCourses.length === 0 ? (*/}
                        {/*    <p>暂无已选课程。</p>*/}
                        {/*) : (*/}
                        {/*    <ul>*/}
                        {/*        {enrolledCourses.map((course) => (*/}
                        {/*            <li key={course.courseId}>{course.courseName}</li>*/}
                        {/*        ))}*/}
                        {/*    </ul>*/}
                        {/*)}*/}

                        {/* 已选课程列表 */}
                        <h3>选课功能</h3>
                        <p>选择你感兴趣的课程并开始学习！</p>
                        <button
                            onClick={() => navigate("/course-selection")}
                            className="select-course-button"
                        >
                            去选课
                        </button>
                    </div>
                )}
            </div>

            {/* 学习统计 */}
            <div className="section">
                <h3>学习统计</h3>
                <p>reading: 12小时</p>
                <p>writing: 8小时</p>
                <p>listening: 5小时</p>
                <button
                    onClick={() => navigate("/ChartPage")}
                    className="view-chart-button"
                >
                    查看图表
                </button>
            </div>

            {/* 激励计划 */}
            <div className="section">
                <h3>激励计划</h3>
                <MotivationalCarousel messages={motivationalMessages}/>
            </div>
        </div>
    )
}

export default Progress;